<?php

/**
 *  Welcome to pdnsFront - the ultra secure and stable PowerDNS+MySQL frontend.
 */

define( 'PDNS_START_TIME', microtime() );

define( 'PDNS_CORE', 1 );

// There should NEVER be any error output
error_reporting( E_ALL | E_STRICT );

// include core class files on demand
function __autoload( $class ){
	// security check
	$class = preg_replace( '#\W#', '', $class );
	$class = strtolower( $class );

	$file = "core/$class.php";
	if( file_exists( $file )){
		require_once( $file );
	}
	else{
		Error::throwError( "require file does not exist: $file" );
	}
}

// loads config from config.php in root directory
$config = Config::getInstance();

if( $config->noConfig ){
	// no config found, show turn-key login page
	// this doesn't work yet, config.php must always exist.  Please edit it manually.
	require_once( 'templates/turnkey/index.php');
	die();
}

// ensure ssl if required
if( $config->ssl ){
	SSL::enforce_ssl();
}

// authenticate
if( isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']) ){
	try{
		$db = DB::getInstance();
		// if there is no exception db connection was good and so user is authneticated
		define( 'PDNS_AUTH', 1 );
	}
	catch( Exception $e ){
		// can not connect to mysql, user not authenticated
	}
}

if(! defined( 'PDNS_AUTH' )){ 
	header('WWW-Authenticate: Basic realm="'. $config->auth_realm .'"');
	header('HTTP/1.0 401 Unauthorized');
	die( "Unauthorized" );
}

// execute the application
Router::route();

Output::setOutput( 'actions', Actions::render() );
Output::setOutput( 'messages', Message::render() );

// show output
require_once( 'templates/default.php' );
